package net.ib.mtalk.ui.start;

import java.util.List;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.AccountAuthToken;
import net.ib.mntalk.protocol.Common.AccountToken;
import net.ib.mntalk.protocol.Session.AcquireAccountAuthTokenRes;
import net.ib.mtalk.R;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.constant.MTalkIntent;
import net.ib.mtalk.constant.PrefsConstant;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.service.SelecterService;
import net.ib.mtalk.util.SmsMessager;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 전화번호 인증화면<br/>
 * Flow: 전화번호로 문자 전송요청 -> 사용자 입력값 비교
 * @author urunimi
 *
 */
public class AuthenticationActivity extends Activity {

	private AuthenticationController mUiController;
	private Context mContext;
	
	private TextView textTitle;
	private EditText editAuthCode;
	
	private AccountAuthToken mAccountAuthToken;
	
	private long mIntervalStartTime;
	private Toast mToast;
	
	private String mCountryCode, mCellNumber;
	
	private int mDeliveryType;
	
	private ProgressDialog mProgressDialog;
	
	public boolean mExistRedirect;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_authentication);
		textTitle = (TextView) findViewById(R.id.textTitle);
		editAuthCode = (EditText) findViewById(R.id.editAuthCode);
		mContext = this;
		
		mExistRedirect = getIntent().getBooleanExtra("redirect", false);
		
		mUiController = new AuthenticationController(this, mHandler);
		
		mProgressDialog = new ProgressDialog(mContext);
		mProgressDialog.setMessage(getString(R.string.waiting));
		mProgressDialog.setCancelable(false);
		
		Bundle bundle = getIntent().getExtras();
		if(bundle == null || bundle.getString(MTalkIntent.KEY_CELL_NUMBER) == null) {
			finish();
			return;
		}
		mCountryCode = bundle.getString(MTalkIntent.KEY_COUNTRY_CODE);
		mCellNumber = bundle.getString(MTalkIntent.KEY_CELL_NUMBER);
		
		final StringBuilder sb = new StringBuilder();
		sb.append(mCountryCode).append(" ").append(Integer.parseInt(mCellNumber));
		textTitle.setText(String.format(getString(R.string.join_send_authentication_number_msg), sb));
		
		setIntervalStartTime();
		mDeliveryType = Common.SELF_SMS;
		mUiController.acquireAccountAuthToServer(mCountryCode, mCellNumber, mDeliveryType);
		
		findViewById(R.id.btnRetry).setOnClickListener(new View.OnClickListener() {
			public void onClick(View arg0) 
			{
				long interval = System.currentTimeMillis() - mIntervalStartTime;
				if(interval < 60000)
				{
					int temp = (int) ((60000 - interval)/1000);
					if(mToast==null)
						mToast = Toast.makeText(mContext,"인증 요청건이 있습니다. " + temp + "초 후 다시 요청해 주세요.",Toast.LENGTH_SHORT);
					else
					{
						mToast.cancel();
						mToast.setText("인증 요청건이 있습니다. " + temp + "초 후 다시 요청해 주세요.");
					}
					
					mToast.show();	
				}
				else
				{
					requestServerSMS();
				}
			}
		});
	}
	
	public void requestServerSMS()
	{
		setIntervalStartTime();
		mDeliveryType = Common.NORMAL_SMS;
		mUiController.acquireAccountAuthToServer(mCountryCode+"", mCellNumber+"", mDeliveryType);
	}
	
	private void setIntervalStartTime()
	{
		mIntervalStartTime = System.currentTimeMillis();
	}
	
	public void onOkClick(View view) {
		if(editAuthCode.getText().toString().trim().length() > 0 && mAccountAuthToken != null) {
			mUiController.acquireAccountToServer(mAccountAuthToken, editAuthCode.getText().toString());
			mProgressDialog.show();
		}
	}
	
	public void onResume()
	{
		super.onResume();
		SelecterService.setMode(this, SelecterService.Mode.FULL_SELECT);
	}
	
	public void onDestroy()
	{
		super.onDestroy();
		if(mProgressDialog != null)
		{
			mProgressDialog.hide();
			mProgressDialog.dismiss();
		}
		
		new Handler().postDelayed(new Runnable(){
			public void run() 
			{
				ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
				List<ActivityManager.RunningTaskInfo> info = am.getRunningTasks(50);
				for(int i = 0 ; i < info.size() ; i++)
				{
					if(info.get(i).topActivity.getPackageName().equals(getPackageName()))
						return;
				}
				
				SelecterService.setMode(mContext, SelecterService.Mode.MONO_SELECT);
			}}, 300);
	}
	
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			switch(msg.what) {
				case HandlerMsgConst.HANDLER_UNKNOWN_ERROR :
					mProgressDialog.hide();
					Toast.makeText(mContext, "HANDLER_UNKNOWN_ERROR", Toast.LENGTH_SHORT).show();
					break;
				case HandlerMsgConst.HANDLER_ACQUIRE_ACCOUNT_AUTH_SUCCESS :
					AcquireAccountAuthTokenRes res = (AcquireAccountAuthTokenRes) msg.obj;
					mAccountAuthToken = res.getAccountAuthToken();
					if(mDeliveryType == Common.SELF_SMS)
						SmsMessager.send(mContext, mCellNumber, new String(res.getAuthCodeEnc().toByteArray())); //self sms 전송
					Toast.makeText(mContext, "HANDLER_ACQUIRE_ACCOUNT_AUTH_SUCCESS", Toast.LENGTH_SHORT).show();
					Toast.makeText(mContext, new String(res.getAuthCodeEnc().toByteArray()), Toast.LENGTH_SHORT).show();
					break;
				case HandlerMsgConst.HANDLER_ACQUIRE_ACCOUNT_AUTH_FAIL :
					Toast.makeText(mContext, "HANDLER_ACQUIRE_ACCOUNT_AUTH_FAIL", Toast.LENGTH_SHORT).show();
					break;
				case HandlerMsgConst.HANDLER_ACQUIRE_ACCOUNT_SUCCESS:
					Toast.makeText(mContext, "HANDLER_ACQUIRE_ACCOUNT_SUCCESS", Toast.LENGTH_SHORT).show();
					mUiController.setUserAccount((AccountToken)msg.obj);
					break;
				case HandlerMsgConst.HANDLER_ACQUIRE_ACCOUNT_FAIL:
					mProgressDialog.hide();
					Toast.makeText(mContext, "HANDLER_ACQUIRE_ACCOUNT_FAIL", Toast.LENGTH_SHORT).show();
					break;
				case HandlerMsgConst.HANDLER_REGISTER_ACCOUNT_SUCCESS:
					Toast.makeText(mContext, "HANDLER_REGISTER_ACCOUNT_SUCCESS", Toast.LENGTH_SHORT).show();
					finish();
					break;
				case HandlerMsgConst.HANDLER_REGISTER_ACCOUNT_FAIL:
					mProgressDialog.hide();
					Toast.makeText(mContext, "HANDLER_REGISTER_ACCOUNT_FAIL", Toast.LENGTH_SHORT).show();
					break;
				default:
					break;
			}
		}
	};
}
